<?php
Yii::import('application.components.Reference');
Yii::import('application.components.U');
class StockMovesController extends GxController
{
    public function actionCreate()
    {
        $model = new StockMoves;
        if (!Yii::app()->request->isAjaxRequest)
            return;
        if (isset($_POST) && !empty($_POST)) {
            foreach ($_POST as $k => $v) {
                if (is_angka($v)) $v = get_number($v);
                $_POST['StockMoves'][$k] = $v;
            }
            $model->attributes = $_POST['StockMoves'];
            $msg = "Data gagal disimpan";
            if ($model->save()) {
                $status = true;
                $msg = "Data berhasil di simpan dengan id " . $model->trans_id;
            } else {
                $msg .= " " . CHtml::errorSummary($model);
                $status = false;
            }
            echo CJSON::encode(array(
                'success' => $status,
                'msg' => $msg));
            Yii::app()->end();
        }
    }
    public function actionCreateKelolaStok()
    {
        if (!Yii::app()->request->isAjaxRequest) return;
        if (isset($_POST) && !empty($_POST)) {
            $msg = 'Pengelolaan persediaan berhasil disimpan.';
            $tgl = $_POST['tran_date'];
            $ket = $_POST['note'];
            $detils = CJSON::decode($_POST['detil']);
            app()->db->autoCommit = false;
            $transaction = Yii::app()->db->beginTransaction();
            try {
                $trans_no = U::get_max_type_no_stock(KELOLASTOK);
                $trans_no++;
                $ref = new Reference();
                $docref = $ref->get_next_reference(KELOLASTOK);
                foreach ($detils as $detil) {
                    U::add_stock_moves(KELOLASTOK, $trans_no, $tgl, $detil['barang_id'], GUDANG_PST, $detil['qty'], $docref, 0);
                }
                U::add_comments(KELOLASTOK, $trans_no, $tgl, $ket);
                $ref->save(KELOLASTOK, $trans_no, $docref);
                $transaction->commit();
                $status = true;
            } catch (Exception $ex) {
                $transaction->rollback();
                $status = false;
                $msg = $ex->getMessage();
            }
            echo CJSON::encode(array(
                'success' => $status,
                'id' => $docref,
                'msg' => $msg));
            Yii::app()->end();
        }
    }
    public function actionCreateSelisihStok()
    {
        if (!Yii::app()->request->isAjaxRequest) return;
        if (isset($_POST) && !empty($_POST)) {
            $msg = 'Selisih persediaan berhasil disimpan.';
            $tgl = $_POST['tran_date'];
            $ket = $_POST['note'];
            $detils = CJSON::decode($_POST['detil']);
            app()->db->autoCommit = false;
            $transaction = Yii::app()->db->beginTransaction();
            try {
                $trans_no = U::get_max_type_no_stock(SELISIHSTOK);
                $trans_no++;
                $ref = new Reference();
                $docref = $ref->get_next_reference(SELISIHSTOK);
                foreach ($detils as $detil) {
                    U::add_stock_moves(SELISIHSTOK, $trans_no, $tgl, $detil['barang_id'], GUDANG_PST, $detil['qty'], $docref, 0);
                    /* @var $barang Barang*/
                    $barang = $this->loadModel($detil['barang_id'], "Barang");
                    $total = $barang->price_buy * $detil['qty'];
                    Yii::import('application.components.Gl');
                    $gl = new Gl();
                    $gl->add_gl(SELISIHSTOK, $trans_no, $tgl, $docref, PERSEDIANBARANGDAGANG, '', '', $total);
                    $gl->add_gl(SELISIHSTOK, $trans_no, $tgl, $docref, SELISIHPERSEDIAAN, '', '', -$total);
                    $gl->validate();
                }
                U::add_comments(SELISIHSTOK, $trans_no, $tgl, $ket);
                $ref->save(SELISIHSTOK, $trans_no, $docref);
                $transaction->commit();
                $status = true;
            } catch (Exception $ex) {
                $transaction->rollback();
                $status = false;
                $msg = $ex->getMessage();
            }
            echo CJSON::encode(array(
                'success' => $status,
                'id' => $docref,
                'msg' => $msg));
            Yii::app()->end();
        }
    }
    public function actionUpdate($id)
    {
        $model = $this->loadModel($id, 'StockMoves');
        if (isset($_POST) && !empty($_POST)) {
            foreach ($_POST as $k => $v) {
                if (is_angka($v)) $v = get_number($v);
                $_POST['StockMoves'][$k] = $v;
            }
            $msg = "Data gagal disimpan";
            $model->attributes = $_POST['StockMoves'];
            if ($model->save()) {
                $status = true;
                $msg = "Data berhasil di simpan dengan id " . $model->trans_id;
            } else {
                $msg .= " " . CHtml::errorSummary($model);
                $status = false;
            }
            if (Yii::app()->request->isAjaxRequest) {
                echo CJSON::encode(array(
                    'success' => $status,
                    'msg' => $msg
                ));
                Yii::app()->end();
            } else {
                $this->redirect(array('view', 'id' => $model->trans_id));
            }
        }
    }
    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest) {
            $msg = 'Data berhasil dihapus.';
            $status = true;
            try {
                $this->loadModel($id, 'StockMoves')->delete();
            } catch (Exception $ex) {
                $status = false;
                $msg = $ex->getMessage();
            }
            echo CJSON::encode(array(
                'success' => $status,
                'msg' => $msg));
            Yii::app()->end();
        } else
            throw new CHttpException(400,
                Yii::t('app', 'Invalid request. Please do not repeat this request again.'));
    }
    public function  actionkelolaStok()
    {
        $kelolaStok = U::get_kelola_stok($_POST['tgl']);
        $total = count($kelolaStok);
        $jsonresult = '{"total":"' . $total . '","results":' . json_encode($kelolaStok) . '}';
        Yii::app()->end($jsonresult);
    }
    public function  actionkelolaStokDetil()
    {
        $trans_no = $_POST['trans_no'];
        $criteria = new CDbCriteria();
        $param = array();
        $criteria->params = $param;
        $criteria->addCondition("type = :type");
        $param[':type'] = KELOLASTOK;
        $criteria->addCondition("trans_no = :trans_no");
        $param[':trans_no'] = $trans_no;
        $criteria->params = $param;
        $model = StockMoves::model()->findAll($criteria);
        $total = StockMoves::model()->count($criteria);
        $this->renderJson($model, $total);
    }
    public function  actionSelisihStok()
    {
        $selisihStok = U::get_selisih_stok($_POST['tgl']);
        $total = count($selisihStok);
        $jsonresult = '{"total":"' . $total . '","results":' . json_encode($selisihStok) . '}';
        Yii::app()->end($jsonresult);
    }
    public function  actionSelisihStokDetil()
    {
        $trans_no = $_POST['trans_no'];
        $criteria = new CDbCriteria();
        $param = array();
        $criteria->params = $param;
        $criteria->addCondition("type = :type");
        $param[':type'] = SELISIHSTOK;
        $criteria->addCondition("trans_no = :trans_no");
        $param[':trans_no'] = $trans_no;
        $criteria->params = $param;
        $model = StockMoves::model()->findAll($criteria);
        $total = StockMoves::model()->count($criteria);
        $this->renderJson($model, $total);
    }
    public function actionIndex()
    {
        if (isset($_POST['limit'])) {
            $limit = $_POST['limit'];
        } else {
            $limit = 20;
        }
        if (isset($_POST['start'])) {
            $start = $_POST['start'];
        } else {
            $start = 0;
        }
        $criteria = new CDbCriteria();
        $param = array();
        if (isset($_POST['mode']) && $_POST['mode'] == "grid_kelola") {
            $criteria->select = "";
        }
        if (isset($_POST['supplier_code'])) {
            $criteria->addCondition("supplier_code like :supplier_code");
            $param[':supplier_code'] = "%" . $_POST['supplier_code'] . "%";
        }
        if (isset($_POST['supplier_name'])) {
            $criteria->addCondition("supplier_name like :supplier_name");
            $param[':supplier_name'] = "%" . $_POST['supplier_name'] . "%";
        }
        if (isset($_POST['status'])) {
            $criteria->addCondition("status = :status");
            $param[':status'] = $_POST['status'];
        }
        $criteria->params = $param;
        if ((isset ($_POST['mode']) && $_POST['mode'] == 'grid') ||
            (isset($_POST['limit']) && isset($_POST['start']))
        ) {
            $criteria->limit = $limit;
            $criteria->offset = $start;
        }
        $model = StockMoves::model()->findAll($criteria);
        $total = StockMoves::model()->count($criteria);
        $this->renderJson($model, $total);
    }
    public function actionSetSaldoAwal()
    {
        if (!Yii::app()->request->isAjaxRequest)
            return;
        if (isset($_POST) && !empty($_POST)) {
            //require_once(Yii::app()->basePath . '/vendors/frontaccounting/ui.inc');
            $status = false;
            $msg = 'Saldo Awal berhasil disimpan.';
            $date = $_POST['trans_date'];
            $user = Yii::app()->user->getId();
            $id = U::get_max_type_no_stock(SALDO_AWAL);
            app()->db->autoCommit = false;
            $transaction = app()->db->beginTransaction();
            try {
//                U::add_gl(SALDO_AWAL, $id, $date, "-", $_POST['account_code'],
//                    '-', get_number($_POST['amount']), $user);
                U::add_stock_moves(SALDO_AWAL, $id, $date, $_POST['barang_id'],
                    GUDANG_PST, get_number($_POST['amount']), "-", 0);
                $transaction->commit();
                $status = true;
            } catch (Exception $ex) {
                $transaction->rollback();
                $status = false;
                $msg = $ex;
            }
            echo CJSON::encode(array(
                'success' => $status,
                'id' => $id,
                'msg' => $msg
            ));
            Yii::app()->end();
        }
    }
}